import numpy as np
from sklearn.linear_model import Ridge
from sklearn.linear_model import SGDRegressor

X = 3 * np.random.rand(100, 1)
y = 4 + 3 * X + np.random.rand(100, 1)

# 这里 alpha 设置为 0.4 对应的就是公式中的α正则项系数，solver=’sag’就是使用随机梯度下降法来求解最优解

ridge_sag = Ridge(alpha=0.4, solver='sag')
ridge_sag.fit(X, y)

print("实际值：", 4 + 3 * 8 + np.random.rand(1, 1))
print("预测值：", ridge_sag.predict([[8]]))
print("截距：", ridge_sag.intercept_)
print("系数：", ridge_sag.coef_)

print('SGDRegressor'.center(60, '-'))
sgd_reg = SGDRegressor(penalty='l2', max_iter=1000)
# 这里 ravel()操作是扁平化
sgd_reg.fit(X, y.ravel())
print("预测值：", sgd_reg.predict([[1.5]]))
print("截距=", sgd_reg.intercept_)
print("系数=", sgd_reg.coef_)
